﻿Imports System.Threading

Public MustInherit Class cConnectionBase

    Public Enum eSocketStatus As Byte
        Offline = 0
        Accepting = 1
        Handshake = 2
        Connected = 3
    End Enum

    Private pPacketQueue As New Collections.Generic.Queue(Of Byte())
    Private pLockObject As New Object
    Private pLockObject1 As New Object
    Private pStatus As eSocketStatus

    MustOverride Sub Send(ByRef packet() As Byte)
    MustOverride Sub Start(ByVal ip As String, ByVal port As UInt32)
    MustOverride Sub Disconnect()

    Public ReadOnly Property Status() As eSocketStatus
        Get
            Do Until Monitor.TryEnter(pLockObject, 5)

            Loop
            Status = pStatus
            Monitor.Exit(pLockObject)
        End Get
    End Property

    Protected Sub Set_Status(ByVal status As eSocketStatus)
        Do Until Monitor.TryEnter(pLockObject, 5)
        Loop

        pStatus = status

        Monitor.Exit(pLockObject)
    End Sub

    Public Function Get_Packet() As Byte()
        Do Until Monitor.TryEnter(pLockObject1, 5)
        Loop

        If pPacketQueue.Count <> 0 Then
            Get_Packet = pPacketQueue.Dequeue()
        Else
            Get_Packet = Nothing
        End If

        Monitor.Exit(pLockObject1)
    End Function

    Protected Sub Add_Packet(ByRef packet() As Byte)
        Do Until Monitor.TryEnter(pLockObject1)
        Loop

        pPacketQueue.Enqueue(packet)

        Monitor.Exit(pLockObject1)
    End Sub

    Sub clear_buffer()
        Do Until Monitor.TryEnter(pLockObject1)
        Loop

        pPacketQueue.Clear()

        Monitor.Exit(pLockObject1)
    End Sub

End Class
